package Stream.并行流;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collector;

//自定义Collector收集器
public class MyCollector {
    public static void main(String[] args) {
        List<String> collect = List.of("D", "A", "N", "d", "i", "n", "g").parallelStream()
                .map(String::toLowerCase)
                //下面自定义收集器拥有等同于ToList的功能
                .collect(Collector.of(
                        //第一个参数,返回容器是什么类型
                        () -> {
                            System.out.println("create new ArrayList" + "Thread:" + Thread.currentThread());
                            return new ArrayList<>();
                        },
                        //第二个参数,累加器
                        (list, item) -> {
                            System.out.println("累加器:" + item + "Thread:" + Thread.currentThread());
                            list.add(item);
                        },
                        //第三个参数,组合器(只有并行流拥有)
                        (left, right) -> {
                            System.out.println("组合器:" + left + "+" + right + "Thread:" + Thread.currentThread());
                            left.addAll(right);
                            return left;
                        },
                        //默认,将累加器中的结果作为最终结果
                        Collector.Characteristics.IDENTITY_FINISH
                        //Collector.Characteristics.CONCURRENT，使用这个会忽略组合器，提高性能，但注意容器必须是线程安全的才可以
                ));
        System.out.println(collect);
    }
}
/*总结：
 * 适用并行流的情况:
 *Aggregation聚合操作:
count
min
maX
sum
average

* Short-circuiting短路操作:
anyMatch
noneMatch
allMatch
findFirst
findAny
 *
 * */
